package com.example.home

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.common.entity.SimpleVideoEntity
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.example.base.RouterPath
import com.example.common.mvi.BaseMviFragment
import com.example.home.adapter.HomeVideoListAdapter
import com.example.home.databinding.FragmentHomeListBinding
import com.example.home.intent.HomeViewIntent
import com.example.home.state.HomeUiState
import com.example.home.vm.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class HomeListFragment : BaseMviFragment<FragmentHomeListBinding>() {

    private val mViewModel:HomeViewModel by activityViewModels()
    private var pageIndex = 1
    private var pageSize = 10
    private var simpleVideoList = mutableListOf<SimpleVideoEntity>()
    private lateinit var mVideoListAdapter:HomeVideoListAdapter
    private var typeId = 0
    private var channelId = ""


    companion object{
        @JvmStatic
        fun newInstance(typeId: Int, channelId: String) =
            HomeListFragment().apply {
                //存值,创建一个新的Bundle对象
                arguments = Bundle().apply {
                    putInt("typeId", typeId)
                    putString("channelId", channelId)
                }
            }
    }
    override fun initViews() {

        arguments?.apply {
            typeId = getInt("typeId")
            channelId = getString("channelId").toString()
        }

        //上拉刷新
        mDataBinding.refreshLayout.setOnRefreshListener{
            pageIndex = 1
            refreshOrMoreList()
        }

        //长列表优化

        var cachePool = RecyclerView.RecycledViewPool().apply {
            setMaxRecycledViews(0,5)//适用于多布局,viewType必须在适配器中的ItemType一致
        }
        mDataBinding.rvHomeList.apply {
            setHasFixedSize(true)//Item是否属于固定大小,减少组件测量时间
            setItemViewCacheSize(40)//设置Item缓存大小
            setRecycledViewPool(cachePool)//设置缓存池
        }

//        //当页面滚动时暂停图片的加载
//        mDataBinding.rvHomeList.addOnScrollListener(object:OnScrollListener(){
//            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
//                if(newState == RecyclerView.SCROLL_STATE_IDLE){
//                    Glide.with(this@HomeListFragment).resumeRequests()
//                }else{
//                    Glide.with(this@HomeListFragment).pauseRequests()
//                }
//            }
//        })



        mVideoListAdapter = HomeVideoListAdapter(simpleVideoList)
        mDataBinding.rvHomeList.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
        mDataBinding.rvHomeList.swapAdapter(mVideoListAdapter,true)//开启屏幕外缓存


        //关闭不需要的动画
        (mDataBinding.rvHomeList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        mVideoListAdapter.apply {
            preloadEndCount = 4
            preloadData = {
                pageIndex += 1
                refreshOrMoreList()
            }
        }

        //设置播放的点击事件,跳转到播放页面
        mVideoListAdapter.setOnItemClickListener(object:HomeVideoListAdapter.OnItemClickListener{
            override fun onItemClick(v: View, position: Int) {
                when(v.id){
                    R.id.iv_video_play->{
                        ARouter.getInstance().build(RouterPath.PATH_PLAY_PAGE)
                            .withInt("typeId",typeId)
                            .withString("channelId",channelId)
                            .withSerializable("videoEntity",simpleVideoList[position])
                            .navigation()
                    }
                }
            }
        })



    }

    override fun getLayoutId(): Int =R.layout.fragment_home_list


    private fun refreshOrMoreList(){
        lifecycleScope.launch {
            //如果当前分类页面是推荐,则加载推荐的视频,我们设置的下标是-1

            if(typeId == -1){
                mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex,pageSize))
            }else{
                mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoListById(channelId,pageIndex,pageSize))
            }
        }
    }

    //清理不是同类的数据
    fun lazyLoadData(){
        if(simpleVideoList.size >0 && simpleVideoList[0].channelid != channelId){
            simpleVideoList.clear()
            mVideoListAdapter.notifyDataSetChanged()
        }
        refreshOrMoreList()
    }

    override suspend fun collectUiState() {
        super.collectUiState()
        mViewModel.uiState.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess->updatePageData(it.list)
                is HomeUiState.LoadSimpleVideoFail->{}
                else->{}
            }
        }
    }

    private fun updatePageData(list:List<SimpleVideoEntity>){
        if (pageIndex == 1){
            mDataBinding.refreshLayout.finishRefresh()
            simpleVideoList.clear()
        }
        simpleVideoList.addAll(list)
        mVideoListAdapter.notifyDataSetChanged()
    }

}